<template>
  <div class="my-exercises">
    <div class="page-header">
      <h2>My Exercises</h2>
      <el-button type="primary" @click="createNewExercise">
        <el-icon><Plus /></el-icon>
        Create New Exercise
      </el-button>
    </div>

    <div class="exercises-container">
      <el-card v-if="loading" class="loading-card">
        <el-skeleton :rows="5" animated />
      </el-card>

      <div v-else-if="exercises.length === 0" class="empty-state">
        <el-empty description="You haven't created any exercises yet">
          <el-button type="primary" @click="createNewExercise">Create Your First Exercise</el-button>
        </el-empty>
      </div>

      <div v-else class="exercises-grid">
        <el-card v-for="exercise in exercises" :key="exercise.id" class="exercise-card">
          <template #header>
            <div class="card-header">
              <h3>{{ exercise.title }}</h3>
              <el-tag size="small">{{ exercise.category }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <p class="description">{{ exercise.description }}</p>
            <div class="stats">
              <div class="stat-item">
                <el-icon><Document /></el-icon>
                <span>{{ exercise.questionCount }} Questions</span>
              </div>
              <div class="stat-item">
                <el-icon><Timer /></el-icon>
                <span>{{ formatDate(exercise.createdAt) }}</span>
              </div>
            </div>
          </div>
          <div class="card-actions">
            <el-button type="primary" @click="viewExercise(exercise.id)">View</el-button>
            <el-button type="success" @click="practiceExercise(exercise.id)">Practice</el-button>
            <el-button type="danger" @click="deleteExercise(exercise.id)">Delete</el-button>
          </div>
        </el-card>
      </div>

      <div class="pagination-container" v-if="exercises.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalExercises"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Document, Timer } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'MyExercises',
  components: {
    Plus,
    Document,
    Timer
  },
  setup() {
    const router = useRouter()
    const exercises = ref([])
    const loading = ref(true)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalExercises = ref(0)

    const fetchExercises = async () => {
      loading.value = true
      try {
        // Replace with actual API call
        // const response = await api.getMyExercises({
        //   page: currentPage.value,
        //   pageSize: pageSize.value
        // })
        // exercises.value = response.data.exercises
        // totalExercises.value = response.data.total

        // Mock data for now
        setTimeout(() => {
          exercises.value = [
            {
              id: 1,
              title: 'JavaScript Basics',
              description: 'Test your knowledge of JavaScript fundamentals',
              category: 'Programming',
              questionCount: 15,
              createdAt: new Date().toISOString()
            },
            {
              id: 2,
              title: 'Vue.js Components',
              description: 'Practice with Vue.js component concepts',
              category: 'Web Development',
              questionCount: 10,
              createdAt: new Date().toISOString()
            }
          ]
          totalExercises.value = 2
          loading.value = false
        }, 1000)
      } catch (error) {
        console.error('Error fetching exercises:', error)
        ElMessage.error('Failed to load exercises')
        loading.value = false
      }
    }

    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchExercises()
    }

    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchExercises()
    }

    const createNewExercise = () => {
      router.push('/dashboard/exercises/create')
    }

    const viewExercise = (id) => {
      router.push(`/dashboard/exercises/${id}`)
    }

    const practiceExercise = (id) => {
      router.push(`/dashboard/exercises/${id}/practice`)
    }

    const deleteExercise = (id) => {
      ElMessageBox.confirm(
        'Are you sure you want to delete this exercise?',
        'Warning',
        {
          confirmButtonText: 'Delete',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      )
        .then(() => {
          // Replace with actual API call
          // await api.deleteExercise(id)
          ElMessage.success('Exercise deleted successfully')
          fetchExercises()
        })
        .catch(() => {
          // User cancelled
        })
    }

    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleDateString()
    }

    onMounted(() => {
      fetchExercises()
    })

    return {
      exercises,
      loading,
      currentPage,
      pageSize,
      totalExercises,
      handleSizeChange,
      handleCurrentChange,
      createNewExercise,
      viewExercise,
      practiceExercise,
      deleteExercise,
      formatDate
    }
  }
}
</script>

<style scoped>
.my-exercises {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.exercises-container {
  background-color: var(--el-bg-color);
  border-radius: 4px;
  padding: 20px;
}

.loading-card {
  margin-bottom: 20px;
}

.empty-state {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

.exercises-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.exercise-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.description {
  flex: 1;
  color: var(--el-text-color-regular);
  font-size: 14px;
  margin-bottom: 15px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.card-actions {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 